use std::net::TcpStream;
use std::net::SocketAddr;

use std::io;
use std::io::{Error, ErrorKind, Write, Read};

use ws;

///连接id计算
static mut CONNECTION_ID: u32 = 1000000000;

pub struct Channel{
    socket: ws::WebSocket<TcpStream>,
    address: SocketAddr,
    id: u32
}

impl Channel{
    pub fn new(address: SocketAddr, socket: ws::WebSocket<TcpStream>) -> Channel{
        let id = new_connection_id();
        Channel{
            socket,
            address,
            id
        }
    }

    pub fn id(&self) -> u32{
        self.id
    }

    ///发送消息
    pub fn send_message(&mut self, message: ws::Message) -> ws::Result<()> {
        let res = self.socket.write_message(message);
        res
    }

    pub fn read_message(&mut self) -> ws::Result<ws::Message>{
        self.socket.read_message()
    }
}

fn new_connection_id() -> u32{
    unsafe {
        if CONNECTION_ID > 9999999998{
            CONNECTION_ID = 1000000000;
        }
        CONNECTION_ID = CONNECTION_ID + 1;
        CONNECTION_ID
    }
}